<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/17
 * Time: 上午9:42
 */

namespace app\index\controller;


use app\common\controller\ActionLogs;
use app\common\controller\AfterPayPutCard;
use app\common\controller\Balance;
use app\common\controller\Bonus;
use app\common\controller\CardDedu;
use app\common\controller\CardMarke;
use app\common\controller\CardPut;
use app\common\controller\CardPuttest;
use app\common\controller\CreateNotify;
use app\common\controller\Deviceobj;
use app\common\controller\FeiePrint;
use app\common\controller\Fenzhang;
use app\common\controller\Fztest;
use app\common\controller\MachExtend;
use app\common\controller\Payinfo;
use app\common\controller\Platurl;
use app\common\controller\TemplateMsg;
use app\common\controller\UserBonusFee;
use app\common\controller\Ydhwork;
use app\common\model\ActionLog;
use app\common\model\Agent;
use app\common\model\CardBonusRule;
use app\common\model\CardConsume;
use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardGeneral;
use app\common\model\CardGivecardLog;
use app\common\model\CardJcList;
use app\common\model\CardJcLog;
use app\common\model\CardJcUserget;
use app\common\model\CardMember;
use app\common\model\CardPaycardlog;
use app\common\model\CardRank;
use app\common\model\CardUserGet;
use app\common\model\CardUserLog;
use app\common\model\CardUserRecLog;
use app\common\model\CardUserUpdate;
use app\common\model\Merchant;
use app\common\model\OpenTemplate;
use app\common\model\Paylog;
use app\common\model\PaymentCardPut;
use app\common\model\PaymentCardPutLog;
use app\common\model\ProfitList;
use app\common\model\System;
use app\common\model\WxOpen;
use app\common\model\WxUser;

use app\common\model\YdhOpen;
use app\common\model\YdhUser;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;
use Wnkj\WnCardObj;

class Wxpaytest extends PayBase
{

    public function get_sub_open_id()
    {
        Session::set('sub_openid', null);
        $request = request();
        $map['id'] = $request->param('id');
        $Merchant = new Merchant();
        $WxOpen = new WxOpen();
        $System = new System();
        $Agent = new Agent();
        $Merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $Merchantinfo['wx_open_id'];
        $users = $WxOpen->where($mab)->find();
        $config = $Agent->where(array('id' => $Merchantinfo['agent']))->find();
//        $config = $System->where(array('id' => 1))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
            // 'partnerkey'=>$agent['partnerkey']
        );

        $weObj = new Wxobjopen($options);

        $openid = Session::get('sub_openid');
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("wxpay/get_sub_open_id", array('id' => $request->param('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {

                $openid = $info['openid'];
                Session::set('sub_openid', $openid);
                $url2 = 'https://' . $_SERVER ['SERVER_NAME'] . url("wxpay/pay", array('id' => $request->param('id'), 'sub_openid' => $openid));
                header("Location: $url2");
            }

        }

    }

    public function pay()
    {
//        $sub_openid = request()->param('sub_openid');
//        if ($sub_openid == '') {
//            $this->get_sub_open_id();
//
//        } else {

        $request = request();
        Session::set('openid', null);
        $map['id'] = $request->param('id');
        $Merchant = new Merchant();
        $Agent = new Agent();
        $System = new System();
        $WxOpen = new WxOpen();
        $user = $Merchant->where($map)->find();
        $config = $Agent->where(array('id' => $user['agent']))->find();
//            $config = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where(array('id' => $user['wx_open_id']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
            // 'partnerkey'=>$agent['partnerkey']
        );

        $weObj = new Wxobjopen($options);
        $openid = Session::get('openid');
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("wxpaytest/pay", array('id' => $request->param('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {
                $openid = $info['openid'];
                session('openid', $openid);
                $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $jssdk = $weObj->getJsSign($url);
            }
        }
        //$this->get_user_info($openid, $request->param('id'));
        //jssdk
        $params['merchantid'] = $user['id'];
        $params['openid'] = $openid;


        //是否已领卡
        $cardinfos = $this->getcarduserinfo($params);
        if ($cardinfos['result_code'] == "SUCCESS") {
            $cardinfo = "";
            $url = "https://" . $_SERVER['HTTP_HOST'] . "/mobile.php?s=/carduser/recharge&card_id=" . $cardinfos['card_id'];
            $cardinfo2 = '<input type="checkbox" id="card_pay" style="width: 15px;"><span class="wxpay_card" >会员卡支付<b style="color:black">[余额:' . $cardinfos['balance'] . ']</b><span><a href="' . $url . '">[在线充值]</a></span></span>';
        } else {
            $cardinfo123 = $this->getcardinfo($params);
            //是否在支付页面中投放
            if ($cardinfo123['result_code'] == "SUCCESS" && $cardinfo123['data'] == "Y") {
                $url = "https://" . $_SERVER['HTTP_HOST'] . "/mobile.php?s=/carduser/opencard/card_id/" . $cardinfos['card_id'].'/mid/'.$map['id'];
                $cardinfo = "";
                $cardinfo2 = "<span class='wxpay_card'>该商户可领取会员卡<span><a href='$url'>点此领取会员卡></a></span></span>";
            }else{
                $cardinfo = "";
                $cardinfo2 = "";
            }
        }



        $this->assign('cardinfo', $cardinfo);
        $this->assign('cardinfo2', $cardinfo2);
        $this->assign('jssdk', $jssdk);
        $this->assign('mach', $user);
        $this->assign('id', $request->param('id'));
        $this->assign('openid', $openid);
        $this->assign("channel", "wxpay");
//            $this->assign('sub_openid', $sub_openid);
//        Session::set('sub_openid', null);
        return $this->fetch();
//        }
    }

    public function card_pay()
    {
        $request = request();

        $params['merchantid'] = $request->param('id');
        $params['openid'] = $request->param('sub_openid');
        $cardinfo = $this->getcarduserinfo($params);

        if ($cardinfo['result_code'] == "SUCCESS") {
            $param['merchantid'] = $request->param('id');
            $param['card_code'] = $cardinfo['code'];
            $param['num'] = $request->param('price');
            $param['method'] = "cardbalancecon";
            $param['device_id'] = "online";
            $param['source'] = "online";
            $re_param = $this->http_post($this->get_api_data($param));

        } else {
            $re_param['result_code'] = "FAIL";
            $re_param['result_msg'] = "未查询到会员卡信息";
        }
        return json($re_param);


    }


    public function pay2()
    {
        $request = request()->param();

        $Paylog = new Paylog();
        $norderid = $Paylog->where(array('orderid' => request()->post('orderid')))->count();
        if ($norderid != 0) {
            $re_param['return_code'] = "FAIL";
            $re_param['return_msg'] = "系统错误,请重试";

        } else {

            $out_trade_no = request()->post('orderid');
            $sub_openid = request()->post('sub_openid');
            $data['orderid'] = $out_trade_no;
            $data['mid'] = request()->param('id');
//            $data['openid'] = request()->post('openid');
            $data['openid'] = request()->post('sub_openid');
            $data['pay_statu'] = 0;
            $data['add_time'] = time();
            $data['attach'] = request()->post('attach');
//            $data['sub_openid'] = $sub_openid;
            $Paylog = new Paylog();
            $Paylog->save($data);
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $map['id'] = $request['id'];
            $config = $Merchant->where($map)->find();

            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();

            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $weObj = new Wxobjopen($options);

            $yf_price = request()->post('price');
            $zkarr['merchantid'] = request()->param('id');
            $zkarr['openid'] = request()->post('sub_openid');
            $zkarr['total_fee'] = $yf_price;
            $zkarr['orderid'] = request()->post('orderid');
            //获取门店折扣
            $MachExtend = new MachExtend();
            $res_machzk = $MachExtend->get_machzk($zkarr);
//            $ActionLogs = new ActionLogs();
//            $ActionLogs->writelog("payos", "wxpay", "pay2", "1:", $res_machzk);
            //已有折扣时将不再调用会员折扣
            if ($res_machzk['is_machzk'] == 'Y') {
                $zk_price = $res_machzk['zk_price'];
//                $ActionLogs->writelog("payos", "wxpay", "pay2", "2:", $zk_price);
            }else {
                $zk_price = $this->getzk($zkarr, "wx_pay");
//                $ActionLogs->writelog("payos", "wxpay", "pay2", "3:", $zk_price);
            }
//            $ActionLogs->writelog("payos", "wxpay", "pay2", "4:", $zk_price);
            $pay_fees = $yf_price - $zk_price;
            $data2['price'] = $pay_fees;
            $Paylog->save($data2, ['orderid' => $out_trade_no]);
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];

            $body = "快捷支付";
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $total_fee = $pay_fees * 100;
            $openid = "";
//            $openid = request()->post('openid');
            $notify_url = 'https://' . $_SERVER ['SERVER_NAME'] . '/api.php';
            $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
            $nonce_str = $weObj->generateNonceStr();


            $arrdata = array(
                "appid" => $appid,
                'sub_appid' => $sub_appid,
                "mch_id" => $mch_id,
                "sub_mch_id" => $sub_mch_id,
                "nonce_str" => $nonce_str,
                "body" => $body,
                "out_trade_no" => $out_trade_no,
                "total_fee" => $total_fee,
                "spbill_create_ip" => $spbill_create_ip,
                "notify_url" => $notify_url,
                "sub_openid" => $sub_openid,
                "receipt" => $config['efp_receipt'],
                'trade_type' => 'JSAPI',
                'profit_sharing' => $config['is_profit'],//是否开启分账
            );

            $pay_xml = $weObj->createWxPackageXml($arrdata);
            $ActionLogs = new ActionLogs();

            $pay_xml = $weObj->get_pay_id($pay_xml);
            $ActionLogs->writelog("payos", "index", "wxpay/pay", "1:", $pay_xml);
//            file_put_contents('/data2/html/payos/public/20191.log',json_encode($arrdata),8);
            if ($pay_xml['return_code'] == "FAIL") {
                $re_param = $pay_xml;
            } else {
                if ($pay_xml['return_code'] == "SUCCESS") {
                    $prepay_id = $pay_xml['prepay_id'];
                    $jsApiObj["appId"] = $appid;
                    $timeStamp = time();
                    $jsApiObj["timeStamp"] = "$timeStamp";
                    $jsApiObj["nonceStr"] = $nonce_str;
                    $jsApiObj["package"] = "prepay_id=" . $prepay_id;
                    $jsApiObj["signType"] = "MD5";
                    $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
                    $re_param['return_code'] = "SUCCESS";
                    $re_param['return_msg'] = "业务处理成功";
                    $re_param['jsApiObj'] = $jsApiObj;

                } else {
                    $re_param['return_code'] = "FAIL";
                    $re_param['return_msg'] = "配置错误,请联系管理员";
                }
            }

        }
        return json($re_param);
    }


    public function payover()
    {
//        try{
            $Paylog = new Paylog();
            $paylogs = $Paylog->where('orderid', request()->param('orderid'))->find();
//            file_put_contents('/data2/html/payos/exelog/wxpayover.log',time()."-1:".json_encode(request()->param()) . PHP_EOL, FILE_APPEND);
            if ($paylogs['pay_fs'] == 8) {
                if ($paylogs['pay_statu'] == 1) {
                    $data = 0;

                    $id = $Paylog->where(['orderid' => request()->param('orderid')])->find();
                    if ($id['tzzt'] == '0') {
                        $s = action('Wxauth/sendtemplate', array($paylogs['mid'], $paylogs['orderid']));
                        $FeiePrint = new FeiePrint();
                        $FeiePrint->sendprint($paylogs['orderid']);
                        $Deviceobj = new Deviceobj();
                        $s=$Deviceobj->ylb_sendvoice($paylogs['orderid']);
//                    action('Index/sendprint', array($id));
                        $da['tzzt'] = 1;
                        $da['tzmsg'] = json_encode($s);
                        $Paylog->save($da, ['orderid' => request()->param('orderid')]);
                    }

                } else {
                    $data = 1;
                }
            } else {
                $request = request();
                $Merchant = new Merchant();
                $Agent = new Agent();
                $WxOpen = new WxOpen();
                $map['id'] = $request->param('id');
                $config = $Merchant->where($map)->find();
                $agent = $Agent->where(array('id' => $config['agent']))->find();
                $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
                $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();

                $options = array(
                    'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                    'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                    'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                );

                $weObj = new Wxobjopen($options);
                $appid = $users['authorizer_appid'];
                $mch_id = $agent['partnerid'];
                $out_trade_no = $request->param('orderid');
                $nonce_str = $weObj->generateNonceStr();
                $sub_mch_id = $config['sub_mch_id'];
                $sub_appid = $userwx['authorizer_appid'];
                $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
                $payorder_xml = $weObj->getPayNum($pay_xml);

//        header("Content-type: text/html; charset=utf-8");

//                $orderno = $payorder_xml['transaction_id'];
                $pay_zt = $payorder_xml['trade_state'];
                if ($pay_zt == "SUCCESS") {
//                    file_put_contents('/data2/html/payos/exelog/wxpayover.log', time().'-1-1:'.$payorder_xml['out_trade_no'] . PHP_EOL, FILE_APPEND);

                    $this->order_query($payorder_xml['out_trade_no']);
                    $data = 0;
//                    echo $data;

//                    file_put_contents('/data2/html/payos/exelog/wxpayover.log', time().'-1-2:'.$data . PHP_EOL, FILE_APPEND);
                } else {
                    $data = 1;
//                    file_put_contents('/data2/html/payos/exelog/wxpayover.log', time().'-1-3:'.$data . PHP_EOL, FILE_APPEND);
                }
            }
//        }catch (\Exception $e){
////            file_put_contents('/data2/html/payos/exelog/wxpayover.log', time().'-e1:'.$e->getMessage() . PHP_EOL, FILE_APPEND);
//            file_put_contents('/data2/html/payos/exelog/lftorderquery.txt', time().'-e11:'.json_encode($e->getMessage() . $e->getFile() . ":" . $e->getLine()), 8);
//            $data = 0;
//        }
//        file_put_contents('/data2/html/payos/exelog/wxpayover.log',time()."-res:".json_encode($data) . PHP_EOL, FILE_APPEND);
        echo $data;
    }

    public function order_query($orderid)
    {
//        try{
            $Paylog = new Paylog();
            $mab['orderid'] = $orderid;
            $ids = $Paylog->where($mab)->field('mid,price,pay_fs')->find();
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $map['id'] = $ids['mid'];
            $config = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $weObj = new Wxobjopen($options);
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no = $orderid;
            $nonce_str = $weObj->generateNonceStr();
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
            $payorder_xml = $weObj->getPayNum($pay_xml);
            $orderno = $payorder_xml['transaction_id'];
            $pay_zt = $payorder_xml['trade_state'];
            if ($pay_zt == "SUCCESS") {
                $Paylog = new Paylog();
                $data['pay_statu'] = 1;
                $data['orderno'] = $orderno;
                $data['ser_openid'] = $payorder_xml['openid'];
                $data['pay_time'] = date('Y-m-d H:i:s', strtotime($payorder_xml['time_end']));
                $data['payinfo'] = json_encode($payorder_xml, true);
                $data['price'] = $payorder_xml['total_fee'] / 100;
                if(isset($payorder_xml['sub_openid'])){
                    $data['sub_openid'] = $payorder_xml['sub_openid'];}
                //费率
                $PayInfo = new Payinfo();
                $data['service_charge'] = $PayInfo->service_charge($ids['mid'], $ids['price'], $ids['pay_fs']);
                //END
                $Paylog->where(['orderid' => $payorder_xml['out_trade_no']])->update($data);
                $id = $Paylog->where(['orderid' => $payorder_xml['out_trade_no']])->find();
                file_put_contents('/data2/html/payos/exelog/wxorderquery.txt', time().'-1:'.json_encode($id), 8);
                if ((int)$id['tzzt'] == 1 ) {

                    return ;
                }
                if ((int)$id['tzzt'] == 0) {
                    $Paylog = new Paylog();
                    $da['tzzt'] = 1;
                    $Paylog->where(['orderid' => $payorder_xml['out_trade_no']])->update($da);
                    //END
                    $s['wx'] = action('Wxauth/sendtemplate', array($id['mid'], $orderid));
                    action('Index/sendprint', array($id));
                    if ($config['is_profit'] == "Y") {
                        $Fenzhang = new Fenzhang();
                        $Fenzhang->createlog($id);
                    }
                    $Deviceobj = new Deviceobj();
                    $s['ylb']=$Deviceobj->ylb_sendvoice($payorder_xml['out_trade_no']);
                    $da['tzmsg'] = json_encode($s);
                    $Paylog->where(['orderid' => $payorder_xml['out_trade_no']])->update($da);
                    //充值
                    if ($id['attach'] == "cardcz") {
                        $updata['mid'] = $id['mid'];
                        $updata['openid'] = $id['openid'];
                        $updata['price'] = $id['price'];
                        $updata['orderid'] = $id['orderid'];
                        $updata['get_card_id'] = $id['cz_card_id'];
                        $this->updata_card_infos($updata);
                    }
                    //扫码
                    if ($id['attach'] == "qrcodezf") {
                        $inc_bonus['orderid'] = $id['orderid'];
                        $inc_bonus['mid'] = $id['mid'];
                        $inc_bonus['openid'] = $id['sub_openid'];
                        $inc_bonus['price'] = $id['price'];
                        $this->inc_bonus($inc_bonus);
                        //增加积分END
                        if (json_decode($id['hx_card'], true) <> '0000') {
                            $hxdata['openid'] = $id['sub_openid'];
                            $hxdata['merchid'] = $id['mid'];
                            $hxdata['cashier'] = $id['cashier'];
                            $hxdata['orderid'] = $id['orderid'];
                            $this->pay_hx_card(json_decode($id['hx_card'], true), $hxdata);
                        }

                    }
                    //购买卡券
                    if ($id['attach'] == "ffcard") {

                        $updata['mid'] = $id['mid'];
                        $updata['openid'] = $id['sub_openid'];
                        $updata['orderid'] = $id['orderid'];
                        $updata['get_card_id'] = $id['cz_card_id'];
                        $res = $this->pay_card_put($updata);

                    }
                    //购买卡券
                    if ($id['attach'] == "ffcardnu") {

                        $updata['mid'] = $id['mid'];
                        $updata['openid'] = $id['sub_openid'];
                        $updata['orderid'] = $id['orderid'];
                        $updata['get_card_id'] = $id['cz_card_id'];

                        $res = $this->pay_card_put_nu($updata);

                    }

                    //购买会员卡
                    if ($id['attach'] == "ffcardbuy") {
//                    file_put_contents('/data2/html/payos/test.txt', 'wxpay-11' . json_encode($id), FILE_APPEND);
                        $paycardus['orderid'] = $id['orderid'];
                        $res = $this->paycardus($paycardus);
//                    file_put_contents('/data2/html/payos/test.txt', 'paycardus-1' . json_encode($res), FILE_APPEND);
                    }

                    //支付后送券
                    if ($id['pay_cate'] == "支付" ) {
                        if ($id['attach'] == "qrcodezf" || $id['attach'] == "") {
                            $paymentcards['orderid'] = $id['orderid'];
                            $paymentcards['openid'] = $id['openid'];
                            $paymentcards['add_time'] = $id['add_time'];
                            $paymentcards['price'] = $id['price'];
                            $paymentcards['mid'] = $id['mid'];
                            $paymentcards['pay_fs'] = $id['pay_fs'];
                            $res = $this->payment_card_put($paymentcards);
                        }
                    }

                    //易订货客户升级
                    if ($id['attach'] == "ydh_upgrade") {
                        $payupgrade['orderid'] = $id['orderid'];
                        $payupgrade['openid'] = $id['openid'];
                        $res = $this->upgradeuser($payupgrade);
                    }

                    //计次卡购买
                    if ($id['attach'] == "pur_cardjc") {
                        $cardjc['orderid'] = $id['orderid'];
                        $cardjc['openid'] = $id['openid'];
                        $res = $this->cardjcpay($cardjc);
                    }
                    $notify_param['merchantid']=$id['mid'];
                    $notify_param['out_trade_no']=$id['orderid'];
                    $CreateNotify=new CreateNotify();
                    $CreateNotify->pay_notify($notify_param);


                }
            }
//        }catch (\Exception $e){
//            file_put_contents('/data2/html/payos/exelog/lftorderquery.txt', time().'-e12:'.json_encode($e->getMessage() . $e->getFile() . ":" . $e->getLine()), 8);
//        }
    }

    public function test()
    {
        $map['orderid'] = "H594-2018090115162537627";
        $id = Paylog::where($map)->find();


        if ($id['attach'] == "ffcard") {

            $updata['mid'] = $id['mid'];
            $updata['openid'] = $id['sub_openid'];
            $updata['orderid'] = $id['orderid'];
            $updata['get_card_id'] = $id['cz_card_id'];

            $res = $this->pay_card_put($updata);
            halt($res);

        }

    }

    // 处理计次卡购买
    public function cardjcpay($param)
    {
        try {
            $CardJcLog = new CardJcLog();
            $CardJcList = new CardJcList();
            $CardJcUserget = new CardJcUserget();
            $CardUserGet = new CardUserGet();
            $loginfo = $CardJcLog->where(['orderid' => $param['orderid']])->find();
            if ($loginfo['statu'] == 2 || $loginfo['statu'] == '2') {
                exit();
            }
            $userinfo = $CardUserGet->where(['id' => $loginfo['us_id']])->find();
            $cardjc = $CardJcList->where(['id' => $loginfo['cardjc_id']])->find();
//            $map['code'] = $userinfo['code'];
//            $map['openid'] = $loginfo['openid'];
//            $map['tims_id'] = $loginfo['cardjc_id'];
//            $userjc = $CardJcUserget->where($map)->find();
//            if ($userjc) {
//                $CardJcUserget->where($map)->setInc('num',$cardjc['pay_num']);
//            }else{
            $data['card_id'] = $userinfo['card_id'];
            $data['mid'] = $userinfo['mid'];
            $data['code'] = $userinfo['code'];
            $data['tims_id'] = $loginfo['cardjc_id'];
            $data['num'] = $cardjc['pay_num'];
            $data['surplus_num'] = $cardjc['pay_num'];
            $data['openid'] = $userinfo['openid'];
            $data['us_id'] = $loginfo['us_id'];
            $data['term_of'] = $cardjc['term_of'];
            $data['addtime'] = time();
            $data['end_time'] = strtotime('+' . $cardjc['term_of'] . ' day');
            $CardJcUserget->allowField(true)->save($data);
//            }
            $CardJcLog->save(['statu' => 2, 'user_id' => $CardJcUserget->id], ['id' => $loginfo['id']]);
            $CardJcList->where(['id' => $loginfo['cardjc_id']])->setInc('rec_num');
        } catch (\Exception $e) {
            $arrc = json_encode(array('code' => '9099', 'message' => $e->getMessage()));

        }
    }

    // 更改易订货客户等级
    public function upgradeuser($param)
    {
        try {

            $YdhUser = new YdhUser();
            $YdhOpen = new YdhOpen();
            $map['openid'] = $param['openid'];
            $userinfo = $YdhUser->where($map)->find();
            $openinfo = $YdhOpen->where(['top_mid' => $userinfo['top_mid']])->find();

            //END
            $data['top_mid'] = $userinfo['top_mid'];
            $data['id'] = $userinfo['user_id'];
            $data['code'] = $userinfo['code'];
            $data['name'] = $userinfo['name'];
            $data['contactor'] = $userinfo['contactor'];
            $data['mobile'] = $userinfo['mobile'];
            $data['customertypeId'] = $openinfo['price_cate_id'];
            $Ydhobj = new Ydhwork();
            $ares = $Ydhobj->update_user($data);

            if ((int)$ares['code'] == 200) {

                $datas['customertypeId'] = $data['customertypeId'];
                $datas['pay_time'] = time();
                $YdhUser->allowField(true)->save($datas, ['id' => $userinfo['id']]);
            }
        } catch (\Exception $e) {
            $arrc = json_encode(array('code' => '9099', 'message' => $e->getMessage()));

        }
    }

    //更新积分余额
    public function updata_card_infos($updata)
    {
        $CardUserGet = new CardUserGet();
        $CardCzLog = new CardCzLog();
        $ComBalance = new Balance();
        $ComCardPut = new \app\common\controller\CardPut();
        $ComBonus = new Bonus();
        $czstatu = $CardCzLog->where('orderid', $updata['orderid'])->value('statu');
        //如果等于1则结束
        if ($czstatu == 1) {
            return 1;
            exit();
        }
        //查询领卡记录
        $user = $CardUserGet->where('id', $updata['get_card_id'])->find();
        //充值记录
        $give_rec_id = $CardCzLog->where('orderid', $updata['orderid'])->value('id');
        $arrss['code'] = $user['code'];
        $arrss['statu'] = 1;
        $CardCzLog->allowField(true)->save($arrss, ['orderid' => $updata['orderid']]);
//        return $user;
        //余额更新
        $arr['card_id'] = $user['card_id'];
        $arr['code'] = $user['code'];
        $arr['openid'] = $updata['openid'];
        $arr['mid'] = $updata['mid'];
        $arr['giveid'] = $CardCzLog->where('orderid', $updata['orderid'])->value('giveid');
        $arr['add_balance'] = $updata['price'];
        $arr['id'] = $user['id'];
        $arr['nickname'] = $user['nickname'];
        $arr['source'] = 2;
        $arr['orderid'] = $updata['orderid'];
        //余额更新
        $arrc = $ComCardPut->checkgive($arr);
        //保存变动记录
        $arr['orderid'] = $updata['orderid'];
        $arr['hx_fs'] = 0;
        $arr['type'] = 1;
        $arr['cate'] = 2;
        $arr['reason'] = 3;
        $arr['source'] = 'online';
        $arr['record_balance'] = 'ONLINERECH';
        $arr['add_bonus'] = $ComBonus->getrechargebonus($arr['giveid'], $arrc['pay_balance'], $user['card_id']);
//        $updataid = $ComBalance->cardupdate($arr, $user, $arrc);

        //冲送
        $arr['give_rec_id'] = $give_rec_id;
        $arr['top_mid'] = $user['top_mid'];
//        $arr['updataid'] = $updataid;
        $resut = $ComBalance->cs_type($arr, $user);
        //END
        //充值记录
        $CardUserRecLog = new CardUserRecLog();
        $recdata['mid'] = $user['mid'];
        $recdata['c_id'] = $user['c_id'];
        $recdata['us_id'] = $user['id'];
        $recdata['openid'] = $user['openid'];
        $recdata['orderid'] = $updata['orderid'];
        $recdata['give_id'] = $arr['giveid'];
        $recdata['pay_cate'] = 0;
        $recdata['source'] = 'online';
        $recdata['action_user'] = $user['nickname'];//操作人
        $recdata['create_time'] = time();
        $CardUserRecLog->allowField(true)->save($recdata);
        //END
        $arrs['rec_id'] = $CardUserRecLog->id;
        $arrs['card_id'] = $user['card_id'];
        $arrs['code'] = $user['code'];
        $arrs['username'] = $user['nickname'];
        $arrs['giveid'] = $arr['giveid'];
        $arrs['orderid'] = $updata['orderid'];
        $arrs['add_balance'] = $arrc['add_balance'];
        $this->cz_bonus_fee($arrs);
        return $resut;
//        }

    }

    //充值 积分 余额  记录
    public function cz_bonus_fee($param)
    {
        try {
            $CardCzLog = new CardCzLog();
            $remark = $CardCzLog->where('orderid', $param['orderid'])->value('remark');
            $option['rec_id'] = $param['rec_id'];
            $option['card_id'] = $param['card_id'];
            $option['poly'] = 'max';
            $option['cs_id'] = $param['giveid'];
            $option['code'] = $param['code'];
            $option['orderid'] = $param['orderid'];
            $option['num'] = $param['add_balance'];
            $option['bd_cate'] = 'balance';
            $option['type'] = 1;//变动 1增加 2减少
            $option['cate'] = 1;  //变动类型
            $option['pay_cate'] = 0; //支付方式
            $option['source'] = 'online';  //来源
            if (!$remark) {
                $remark = '充值';
            }
            $option['remark'] = $remark; //备注
            $option['action_user'] = $param['username'];//操作人
            $Fztest = new WnCardObj($option);
            $Fztest->init();
        } catch (\Exception $e) {
            $arrc = json_encode(array('code' => '9099', 'message' => $e->getMessage()));

        }
    }

    //付费购券
    /*
     *  orderid  get_card_id  mid
     * */
    public function pay_card_put($updata)
    {

        try {
            $CardUserGet = new CardUserGet();
            $CardPaycardlog = new CardPaycardlog();
            $ComCardPut = new \app\common\controller\CardPut();
            $paycardlost = $CardPaycardlog->where('orderid', $updata['orderid'])->field('id,putstatu')->find();

            //如果等于1则结束
            if ($paycardlost['putstatu'] == 1) {
                exit();
            }
            //如果领卡记录等于0
            if ($updata['get_card_id'] == 0) {
                exit();
            }
            //查询领卡记录
            $user = $CardUserGet->where('id', $updata['get_card_id'])->field('card_id,code,id,top_mid,openid,nickname')->find();
            //发放卡券
            $arr['card_id'] = $user['card_id'];
            $arr['code'] = $user['code'];
            $arr['openid'] = $user['openid'];
            $arr['nickname'] = $user['nickname'];
            $arr['mid'] = $updata['mid'];
            $arr['give_rec_id'] = $paycardlost['id'];
            $arr['giveid'] = $CardPaycardlog->where('orderid', $updata['orderid'])->value('fid');
            $arr['id'] = $user['id'];
            $arr['top_mid'] = $user['top_mid'];

            //余额更新
            $arrc = $ComCardPut->payregsgive($arr);

            $CardPaycardlog->allowField(true)->save(['putstatu' => 1], ['orderid' => $updata['orderid']]);
        } catch (\Exception $e) {
            $arrc = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
        }
        return $arrc;
    }

    //付费购券
    /*
     *  orderid  get_card_id  mid
     * */
    public function pay_card_put_nu($updata)
    {
        try {
            $CardPaycardlog = new CardPaycardlog();
            $ComCardPut = new \app\common\controller\CardPut();
            $paycardlost = $CardPaycardlog->where('orderid', $updata['orderid'])->field('id,putstatu')->find();
            //如果等于1则结束
            if ($paycardlost['putstatu'] == 1) {
                exit();
            }
            //如果领卡记录等于0
//            if ($updata['get_card_id'] == 0) {
//                exit();
//            }
            //查询领卡记录

            //发放卡券
            $arr['card_id'] = '';
            $arr['code'] = 'public';
            $arr['openid'] = $updata['openid'];
//            $arr['nickname'] = $user['nickname'];
            $arr['mid'] = $updata['mid'];
            $arr['give_rec_id'] = $paycardlost['id'];
            $arr['giveid'] = $CardPaycardlog->where('orderid', $updata['orderid'])->value('fid');


            $arrc = $ComCardPut->payregsgivenotuser($arr);
            $CardPaycardlog->allowField(true)->save(['putstatu' => 1], ['orderid' => $updata['orderid']]);
        } catch (\Exception $e) {
            $arrc = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
        }
        return $arrc;
    }

    //支付后送券
    /*
     *  orderid  openid  mid  price add_time
     * */
    public function payment_card_put($param)
    {
        try {
            //判断是否微信支付
            if ($param['pay_fs'] == 0 || $param['pay_fs'] == 2) {
                $AfterPayPutCard = new AfterPayPutCard();
                $arrc = $AfterPayPutCard->paymentcard($param);
            } else {
                $arrc = 'error1';
            }
        } catch (\Exception $e) {
            $arrc = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
            $ActionLogs = new ActionLogs();
            $ActionLogs->writelog("payos","payment","paycards","1:",$arrc);

        }
        return $arrc;
    }

    public function paycardus($arr)
    {

        try {

            $CardUserGet = new CardUserGet();
            $CardPaycardlog = new CardPaycardlog();
            $paycardus = $CardPaycardlog->where(['orderid' => $arr['orderid']])->field('openid,user_code,putstatu')->find();
            //等于1 则结束
            if ($paycardus['putstatu'] == 1) {
                exit();
            };
            $user = $CardUserGet->where(['code' => $paycardus['user_code'], 'openid' => $paycardus['openid']])->field('openid,code,card_id')->find();
            $CardPaycardlog->allowField(true)->save(['paystatu' => 1, 'paytime' => time()], ['orderid' => $arr['orderid']]);
            if ($user) {
                $data['membership_number'] = $paycardus['user_code'];
                $data['code'] = $paycardus['user_code'];
                $data['card_id'] = $user['card_id'];
                $data['openid'] = $user['openid'];
                $CardMarke = new CardMarke();
                $res = $CardMarke->activcardus($data);
                if ($res['errcode'] == 0) {
                    $CardPaycardlog->allowField(true)->save(['putstatu' => 1], ['orderid' => $arr['orderid']]);
                }
            } else {
                $res = '';
            }
            return $res;
        } catch (\Exception $e) {
            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
        }
        return $res;
    }

    public function updata_card_info($updata)
    {
        $CardUserGet = new CardUserGet();
        $CardUserUpdate = new CardUserUpdate();
        $CardCzLog = new CardCzLog();
        //查询领卡记录
        $cardinfo = $CardUserGet->where('id', $updata['get_card_id'])->find();
        //余额更新
        $arr['card_id'] = $cardinfo['card_id'];
        $arr['code'] = $cardinfo['code'];
        $arr['openid'] = $updata['openid'];
        $arr['mid'] = $updata['mid'];
        //赠送金额
        $zsprice = $CardCzLog->where('orderid', $updata['orderid'])->value('zs_price');
        if ($zsprice) {
            $arr['add_balance'] = $updata['price'] + $zsprice;
        } else {
            $arr['add_balance'] = $updata['price'];
        }
        $CardUserGet->where('id', $updata['get_card_id'])->setInc('balance', $arr['add_balance']);
        //余额变动模版消息
        $data_tpl['openid'] = $arr['openid'];
        $data_tpl['balance'] = $CardUserGet->where(array('card_id' => $arr['card_id'], 'code' => $arr['code']))->value('balance');
        $data_tpl['card_id'] = $arr['card_id'];
        $data_tpl['add_balance'] = $arr['add_balance'];
        $data_tpl['type'] = 1;
        $resu['balance'] = $this->tpl_cz_mesg($data_tpl);       //模版消息结果

        //积分变动
        $CardMember = new CardMember();
        $card = $CardMember->where('card_id', $cardinfo['card_id'])->find();
        if ($card['supply_bonus'] == 1) {
            $giveid = $CardCzLog->where('orderid', $updata['orderid'])->value('giveid');    //获取该笔订单规则ID
            if ($giveid > 0) {                                                                               //充值规则
                $bonusarr['orderid'] = $updata['orderid'];                  //订单编号
                $bonusarr['code'] = $cardinfo['code'];                       //会员卡code
                $bonusarr['card_id'] = $cardinfo['card_id'];                //会员卡card_id
                $bonusarr['get_card_id'] = $cardinfo['id'];                 //领取id
                //冲送积分
                $resut['bonus'] = $this->cs_bonus($bonusarr);                //赠送积分
            } else {                                                                                        //无充值规则
                //设置积分
                $bonus_rule = json_decode($card['bonus_rule'], true);
                //比例和积分
                $bili = @($bonus_rule['increase_bonus'] / $bonus_rule['cost_money_unit']);
                $add_bonus = floor($arr['add_balance'] * $bili);
                //同步微信数据
                $bonus['code'] = $cardinfo['code'];
                $bonus['card_id'] = $cardinfo['card_id'];
                $bonus['record_bonus'] = '充值赠送';
                $bonus['add_bonus'] = $add_bonus;
                $resu['bonus'] = $this->bonusgive($bonus);        //积分结果
                if ($resu['bonus']['errcode'] == 0) {
                    $datas['add_bonus'] = $add_bonus;
                    $datas['record_bonus'] = '充值赠送';
                }
            }
        }

        //充值送券模版消息
        $cardarr['orderid'] = $updata['orderid'];
        $cardarr['openid'] = $cardinfo['openid'];
        $cardarr['nickname'] = $cardinfo['nickname'];
        $resut['card'] = $this->cs_card($cardarr);   //赠送卡券结果
        //记录更新
//        $datas['mid'] = $arr['mid'];                        //mid
//        $datas['openid'] = $cardinfo['openid'];             //openid
//        $datas['code'] = $cardinfo['code'];                 //code
//        $datas['card_id'] = $cardinfo['card_id'];           //card_id
//        $datas['create_time'] = time();                     //时间
//        $datas['outerid'] = $arr['mid'];                    //来源
//        $datas['add_balance'] = $arr['add_balance'];        //增加金额
//        $datas['pay_balance'] = $updata['price'];           //支付金额
//        $datas['type'] = 1;                                   //类别
//        $datas['hx_fs'] = 8;
//        $datas['cate'] = 2;
//        $datas['reason'] = 3;
//        $datas['source'] = 2;
//        $datas['record_balance'] = '在线充值';              //在线充值
//        $datas['tplmesg_info'] = json_encode($resu);        //模版消息结果
//        $datas['tplmesg_info_zs'] = json_encode($resut);    //赠送模版消息结果
////        $datas['hx_fs'] = '在线充值';                       //
//        $datas['con_username'] = 'ONLINERECH';
//
//        $CardUserUpdate->allowField(true)->save($datas);        //保存记录

    }

    //赠送积分
    /*
     * card_id(会员卡ID)，add_bonus(变动积分)，record_bonus（变动说明）code（用户会员卡编号） orderid(订单编号)
     * */
    public function cz_bonus()
    {

    }

    /*
     * 积分规则
     * card_id(会员卡ID)，add_bonus(变动积分)，record_bonus（变动说明）code（用户会员卡编号）
     *
     */
    public function bonusgive($arr)
    {
        $CardBonusRule = new CardBonusRule();
//        $arr = [];
        //禁止规则
        $map['end_time'] = ['egt', time()];
        $map['card_id'] = $arr['card_id'];
        $map['type'] = 1;
        $map['statu'] = 0;
        $ruledis = $CardBonusRule->where($map)->find();
        if (empty($ruledis)) {
            //多倍规则
            $mab['end_time'] = ['egt', time()];
            $mab['card_id'] = $arr['card_id'];
            $mab['type'] = 2;
            $mab['statu'] = 0;
            $rulemax = $CardBonusRule->where($mab)->find();
            //多倍积分
            if ($rulemax) {
                $CardUserGet = new CardUserGet();
                $barr['add_bonus'] = $arr['add_bonus'] * $rulemax['bonus_max'];               //积分变动
                $barr['card_id'] = $arr['card_id'];                                         //卡券ID
                $barr['code'] = $arr['code'];                                               //卡券CODE
                $barr['record_bonus'] = $arr['record_bonus'];                               //说明
                $res = $this->updatebonus($barr);
                if ($res['errcode'] == 0) {
                    $mad['card_id'] = $arr['card_id'];
                    $mad['code'] = $arr['code'];
                    $CardUserGet->where($mad)->setField('bonus', $res['result_bonus']);

                    $datas = $res;
                } else {
                    $datas = ['msg' => $res['errmsg'], 'code' => '9002'];
                }
                //普通积分
            } else {
                $CardUserGet = new CardUserGet();
                $barr['add_bonus'] = $arr['add_bonus'];               //积分变动
                $barr['card_id'] = $arr['card_id'];                                         //卡券ID
                $barr['code'] = $arr['code'];                                               //卡券CODE
                $barr['record_bonus'] = $arr['record_bonus'];                               //说明
                $res = $this->updatebonus($barr);
                if ($res['errcode'] == 0) {
                    $mad['card_id'] = $arr['card_id'];
                    $mad['code'] = $arr['code'];
                    $CardUserGet->where($mad)->setField('bonus', $res['result_bonus']);

                    $datas = $res;
                } else {
                    $datas = ['msg' => $res['errmsg'], 'code' => '9002'];
                }
            }
        } else {
            $datas = ['msg' => '该时间段内不可积分', 'code' => '9004'];
        }
        return $datas;
    }


    /*
     * 积分
     * 参数 orderid（订单id）code（用户会员卡编号）card_id（会员卡id） get_card_id（领卡记录id）
     *
     */
    private function cs_bonus($param)
    {
        $CardCzLog = new CardCzLog();
        $CardCzgive = new CardCzgive();
        $CardUserGet = new CardUserGet();
        $giveid = $CardCzLog->where('orderid', $param['orderid'])->value('giveid');
        $zs_bonus = $CardCzgive->where('id', $giveid)->value('bonus');
        if ($zs_bonus > 0) {
            //同步微信数据
            $bonusb['code'] = $param['code'];
            $bonusb['card_id'] = $param['card_id'];
            $bonusb['record_bonus'] = '充值赠送';
            $bonusb['add_bonus'] = $zs_bonus;
            $resut = $this->updatebonus($bonusb);
            if ($resut['errcode'] == 0) {
                //更新积分
                $CardUserGet->where('id', $param['get_card_id'])->setField('bonus', $resut['result_bonus']);
                return $resut;
            } else {
                $resut = ['code' => 9001, 'message' => '赠送失败！'];
                return $resut;
            }

        } else {
            $resut = ['code' => 9002, 'message' => '无赠送积分！'];
            return $resut;
        }
    }


    /*
     * 送券
     * 参数 orderid（订单id）openid（用户openid）nickname（用户昵称）
     *
     */
    private function cs_card($param)
    {
        $CardCzLog = new CardCzLog();
        $CardCzgive = new CardCzgive();
        $giveid = $CardCzLog->where('orderid', $param['orderid'])->value('giveid');
        $zs_card = $CardCzgive->where('id', $giveid)->value('zs_card');
        if ($zs_card > 0) {
            //多张
            if ($zs_card > 1) {
                $data_tpl_zs['card_id'] = $CardCzgive->where('id', $giveid)->value('card_id');
                $data_tpl_zs['openid'] = $param['openid'];
                $data_tpl_zs['give'] = $giveid;
                $data_tpl_zs['name'] = $param['nickname'];
                $data_tpl_zs['title'] = '充值赠送';

                $resut = $this->tpl_zs_mesg_list($data_tpl_zs);

                $mesg = $resut;
                $czdata['statu'] = 1;
                $CardCzLog->save($czdata, ['orderid' => $param['orderid']]);
            } else {
                //单张
                $data_tpl_zs['openid'] = $param['openid'];
                $data_tpl_zs['card_id'] = $CardCzgive->where('id', $giveid)->value('zs_card_id');
                $data_tpl_zs['name'] = $param['nickname'];
                $data_tpl_zs['title'] = '充值赠送';
                //获取卡券过期状态
                $resut = filteroffcard($data_tpl_zs['card_id']);
                if ($resut == true) {
                    $resut = $this->tpl_zs_mesg($data_tpl_zs);
                } else {
                    $resut = '送券已过期';
                }
                $mesg = $resut;
                $czdata['statu'] = 1;
                $CardCzLog->save($czdata, ['orderid' => $param['orderid']]);
            }
        }
        $mesg['errmsg'] = '无送券';
        return $mesg;
    }


    //增加积分
    /*
     * card_id / openid  / price
     * */
    private function inc_bonus($arr)
    {
        try {
            $map['top_mid'] = $this->get_top_mid($arr);;
            $map['openid'] = $arr['openid'];
            $map['card_type'] = ['eq', 'MEMBER_CARD'];
            $map['fire'] = 1;
            $map['have'] = 1;
            $CardUserGet = new CardUserGet();
            $carduser = $CardUserGet->where($map)->field('card_id,code,id,top_mid,nickname,openid,code')->find();
            if ($carduser) {
                $bonus_rule_bili = $this->bonusgivess($carduser);
                if ($bonus_rule_bili > 0) {
                    $CardUserUpdate = new CardUserUpdate();
                    $isorder = $CardUserUpdate->where(['orderid' => $arr['orderid']])->find();
                    if (!$isorder) {
                        //积分变动
                        $CardMember = new CardMember();
                        $card = $CardMember->where('card_id', $carduser['card_id'])->field('supply_bonus,id,bonus_rule')->find();
                        if ($card['supply_bonus'] == 1) {
                            //设置积分
                            $bonus_rule = json_decode($card['bonus_rule'], true);
                            //比例和积分
                            $bili = @($bonus_rule['increase_bonus'] / $bonus_rule['cost_money_unit']);
                            $add_bonus = floor($arr['price'] * $bili);
                            //同步微信数据
                            $datas['orderid'] = $arr['orderid'];
                            $datas['add_bonus'] = $add_bonus;
                            $datas['record_bonus'] = '消费赠送';
                            $datas['mid'] = $arr['mid'];
                            $datas['card_id'] = $carduser['card_id'];
                            $datas['code'] = $carduser['code'];
                            $datas['create_time'] = time();
                            $datas['outerid'] = $arr['mid'];
                            $datas['add_bonus'] = $add_bonus;
                            $datas['pay_balance'] = $arr['price'];
                            $datas['record_balance'] = '扫码支付';
                            $datas['hx_fs'] = 29;
                            $datas['type'] = 6;
                            $datas['cate'] = 1;
                            $datas['reason'] = 1;
                            $datas['source'] = 'online';
                            $datas['con_username'] = 'PAYQRCODE';
//                            $CardUserUpdate->allowField(true)->save($datas);
                            $this->qrcodepaybonus($datas);
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            file_put_contents('/data2/html/payos/qrcodezf.txt', 'e:' . json_encode($res, JSON_UNESCAPED_UNICODE), FILE_APPEND);
        }
    }

    public function bonusgivess($param)
    {

        $CardBonusRule = new CardBonusRule();
        //禁止规则
        $map['end_time'] = ['egt', time()];
        $map['card_id'] = $param['card_id'];
        $map['statu'] = 0;
        $rule = $CardBonusRule->where($map)->find();
        if ($rule) {
            if ($rule['type'] == 1) {
                $bili = 0;
            } else {
                $bili = $rule['bonus_max'];
            }
        } else {
            //普通
            $bili = 1;
        }
        return $bili;
    }

    //扫码支付积分
    private function qrcodepaybonus($param)
    {
        try {
            $data['card_id'] = $param['card_id'];
            $data['code'] = $param['code'];
            $data['num'] = $param['add_bonus'];
            $data['remark'] = '消费赠送';
            $data['type'] = 1;
            $data['cate'] = 4;
            $data['pay_cate'] = 0;
            $data['source'] = 'online';
            $data['orderid'] = '';
            $data['bd_cate'] = 'bonus';
            $data['action_user'] = 'PAYQRCODE';//操作人
            $data['orderid'] = $param['orderid'];
            $Fztest = new WnCardObj($data);
            $Fztest->init();
        } catch (\Exception $e) {
            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            file_put_contents('/data2/html/payos/qrcodepaybonus.txt', 'e:' . json_encode($res, JSON_UNESCAPED_UNICODE), FILE_APPEND);
        }
    }

    private function rec_user_bonus($param)
    {
        try {
            $CardMember = new CardMember();
            if (isset($arr['nickname'])) {
                $bonusb['con_username'] = $param['nickname'];
            } else {
                $bonusb['con_username'] = $param['con_username'];
            }
            $bonusb['record_bonus'] = $param['record_balance'];
            $bonusb['us_id'] = $param['us_id'];
            $bonusb['top_mid'] = $param['top_mid'];
            $bonusb['mid'] = $param['mid'];
            $bonusb['c_id'] = $param['c_id'];
            $bonusb['openid'] = $param['openid'];
            $bonusb['card_id'] = $param['card_id'];
            $bonusb['code'] = $param['code'];
            $bonusb['reason'] = $param['reason'];
            $bonusb['bonus'] = $param['add_bonus'];
            $bonusb['pay_cate'] = 0;
            $bonusb['cate'] = 2;
            $bonusb['source'] = $param['source'];
            $bonusb['orderid'] = $param['orderid'];
            $type = $param['type'] == 2 ? 2 : 1;
            $UserBonusFee = new UserBonusFee();
            $UserBonusFee->rec_user_bonus($bonusb, $type);
        } catch (\Exception $e) {
            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            file_put_contents('/data2/html/payos/qrcodezf.txt', 'wxpay-21' . json_encode($res, JSON_UNESCAPED_UNICODE), FILE_APPEND);
        }
    }

    public function rec_cardlogs($arr)
    {
        try {
            $CardUserLog = new CardUserLog();
            $data['orderid'] = $arr['orderid'];
            $data['mid'] = $arr['mid'];
            $data['top_mid'] = $arr['top_mid'];
            $data['up_id'] = $arr['up_id'];
            $data['openid'] = $arr['openid'];
            $data['con_username'] = $arr['con_username'];
            $data['c_id'] = $arr['c_id'];
            $data['us_c_id'] = $arr['us_c_id'];
            $data['card_id'] = $arr['card_id'];
            $data['code'] = $arr['code'];
            $data['num'] = $arr['add_bonus'];
            if (isset($arr['record_balance'])) {
                $data['record'] = $arr['record_balance'];           //记录
            }
            $data['type'] = $arr['type'];               //1充值/2核销
            $data['cate'] = $arr['cate'];               //1积分/2余额
            $data['reason'] = $arr['reason'];           //原因
            $data['source'] = $arr['source'];           //来源
            $data['create_time'] = time();
            $res = $CardUserLog->allowField(true)->save($data);
        } catch (\Exception $e) {
            $res = ['errcode' => 9999, 'message' => $e->getMessage()];
//            file_put_contents('/data2/html/payos/rec_cardlogs.txt', 'e:' . json_encode($res), FILE_APPEND);
        }
//        file_put_contents('/data2/html/payos/test.txt', 'bonus-1' . json_encode($res), FILE_APPEND);
    }

    //获取会员卡折扣
    /*
     * openid  /  mid
     * */
    private function getzk($param,$type)
    {
        $openid = $param['openid'];
        $CardDedu = new CardDedu();
        $CardMember = new CardMember();
        $arr['add_balance'] = $param['total_fee'];


        $user = $this->get_card_userinfo($param['merchantid'], $openid);

        if ($user) {
            $cardus = $CardMember->where(array('card_id' => $user['card_id']))->find();

            $arrc = $CardDedu->getzk($arr, $user, $cardus,$type);
        } else {
//            $datas['add_balance'] = 0;
//            $datas['del_balance'] = 0;                                               //实际支付额
            $arrc['dis_card_zk'] = 0;                                                 //会员折扣
            $arrc['vip_card_zk'] = 0;                                                 //等级折扣
            $arrc['gel_card_zk'] = 0;                                                 //卡券折扣
            $arrc['hx_card'] = "0000";                                                //要核销的卡券
            $arrc['yf_balance'] = $arr['add_balance'];                                //应付金额

        }
        $zk_price = $arrc['dis_card_zk'] + $arrc['vip_card_zk'] + $arrc['gel_card_zk'];
        $datas['dis_card_zk'] = $arrc['dis_card_zk'];                                                 //会员折扣
        $datas['vip_card_zk'] = $arrc['vip_card_zk'];                                                     //等级折扣
        $datas['gel_card_zk'] = $arrc['gel_card_zk'];
        $datas['yf_price'] = $arr['add_balance'];
        $datas['hx_card'] = $arrc['hx_card'];
        $datas['zk_price'] = $zk_price;

        $Paylog = new Paylog();
        $Paylog->save($datas, array('orderid' => $param['orderid']));

        return $zk_price;

    }


    /*
     * 核销抵扣卡券
     *
     * $arr   card_id  code             好核销的卡券数组
     * $data  openid merchid cashier  orderid  核销记录参数
     * */
    private function pay_hx_card($arr, $data)
    {
        $CardUserGet = new CardUserGet();
        $CardConsume = new CardConsume();
        $Paylog = new \app\common\model\Paylog();
        if (isset($arr) && is_array($arr)) {
//            $openid = $this->getsubopenid($data);
            foreach ($arr as $k => $v) {
                $options = $this->options($v['card_id']);
                $wxObj = new Wxobjopen($options);
                $res[$k] = $wxObj->consumeCode($v);
//                return $res;
                if (isset($res[$k]['errcode']) && $res[$k]['errcode'] == 0) {
//                    $CardUserGet->save(['statu' => 2], $v);
                    $CardUserGet->where(['code'=>$v['code'],'card_id'=>$v['card_id']])->update(['statu' => 2]);
                    //核销记录
                    $conlog[$k]['card_id'] = $v['card_id'];
                    $conlog[$k]['code'] = $v['code'];
                    $conlog[$k]['card_type'] = get_cardid_type_lden($v['card_id']);
                    $conlog[$k]['openid'] = $data['openid'];
                    $conlog[$k]['mid'] = $data['merchid'];
                    $conlog[$k]['hx_fs'] = '消费抵扣';
                    $conlog[$k]['con_username'] = $data['cashier'];
                    $conlog[$k]['create_time'] = time();
                    $resu = '0000';
                } else {
                    $resu = '9009';
                    $CardUserGet->where(['code'=>$v['code'],'card_id'=>$v['card_id']])->update(['statu' => 2]);
                }
            }
            if (isset($conlog)) {
                $CardConsume->allowField(true)->saveAll($conlog);
            }
            $pdata['hx_card_res'] = json_encode($res, JSON_UNESCAPED_UNICODE);
            $Paylog->allowField(true)->save($pdata, ['orderid' => $data['orderid']]);
            $resu = $pdata['hx_card_res'];
        } else {
            $resu = '9009';
        }
        return $resu;
    }



    //获取topmid
    /*
     * mid
     * */
    private function get_top_mid($arr)
    {
        $Merchant = new Merchant();
        $top_mid = $Merchant->where(['id' => $arr['mid']])->value('top_mid');
        return $top_mid;
    }


    /*余额变动模版消息发送
     * 参数 card_id（会员卡编号），type（变动类型1：充值，2：消费），add_balance（变动余额），balance（余额）；
     *
     * */
    public function tpl_cz_mesg($arr)
    {
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $map['id'] = $CardMember->where('card_id', $arr['card_id'])->value('mid');
        $wx_open_id = $Merchant->where($map)->value('wx_open_id');
        //初始化微信类
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mid = $this->getmid($arr['card_id']);
        $map['id'] = $mid;
        $merchantiinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantiinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantiinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $wxObj = new Wxobjopen($options);
        $OpenTemplate = new OpenTemplate();
        $templateid = $OpenTemplate->where(['type' => 'card_ye_tpl', 'wx_open_id' => $wx_open_id])->value('template_id');
        switch ($arr['type']) {
            case "1":
                $type = "充值";
                break;
            case "2":
                $type = "消费";
                break;
            default:
                $type = "未知";
                break;
        }
        $add_balance = floor($arr['add_balance'] * 100) / 100;
        $balance = floor($arr['balance'] * 100) / 100;
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => trim($templateid),
            'url' => "",
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => '余额' . $type . "提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'keyword2' => ['value' => '余额' . $type, 'color' => '#FF0000'],
                'keyword3' => ['value' => $add_balance . '元', 'color' => '#000'],
                'keyword4' => ['value' => $balance . '元', 'color' => '#000'],
                'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
            )
        );
        $res = $wxObj->sendTemplateMessage($template);
        if ($res['errcode'] == 0) {
            $CardUserGet = new CardUserGet();
            $arrp['card_id'] = $arr['card_id'];
            $arrp['code'] = $CardUserGet->where(['openid' => $arr['openid'], 'card_id' => $arr['card_id']])->value('code');
            $arrp['price'] = $balance;
            $resu = $this->updateprice($arrp);
            $rarr = $resu;
        } else {
            $rarr = $res;
        }
        return $rarr;
    }

    //余额更新
    public function updateprice($arr)
    {
        //实例化微信
        $options = $this->options($arr['card_id']);
        $WxObj = new Wxobjopen($options);
        $data = [
            'code' => $arr['code'],
            'card_id' => $arr['card_id'],
            'custom_field_value2' => $arr['price'] . '元',
            'notify_optional' => [
                'is_notify_bonus' => false,
                'is_notify_balance' => false,
                'is_notify_custom_field2' => false,
            ],
        ];
        $res = $WxObj->updateUserInfo($data);
        return $res;
    }

    //积分更新
    public function updatebonus($arr)
    {

        //实例化微信
        //初始化微信类
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mid = $this->getmid($arr['card_id']);
        $map['id'] = $mid;
        $merchantiinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantiinfo['wx_open_id'];
        $config = $Agent->where(array('id' => $merchantiinfo['agent']))->find();
//        $config = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $WxObj = new Wxobjopen($options);
        $data = [
            'code' => $arr['code'],
            'card_id' => $arr['card_id'],
            'record_bonus' => $arr['record_bonus'],
            'add_bonus' => $arr['add_bonus'],
            'notify_optional' => [
                'is_notify_bonus' => true,
                'is_notify_balance' => true,
                'is_notify_custom_field1' => true,
            ],
        ];
        $res = $WxObj->updateUserInfo($data);
        return $res;
    }

    //充值赠送卡券
    public function tpl_zs_mesg($arr)
    {
        $System = new System();
        $WxOpen = new WxOpen();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $mid = $this->getmid($arr['card_id']);
        $map['id'] = $mid;
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $weObj = new Wxobjopen($options);
        //模板ID
        $OpenTemplate = new OpenTemplate();
        $templateid = $OpenTemplate->where(['type' => 'card_zs_tpl', 'wx_open_id' => $mab['id']])->value('template_id');
        $Platurl = new Platurl();
        $agent_url = $Platurl->getagenturl('card_id', $arr['card_id']);
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => $templateid,
            'url' => $agent_url . "/mobile.php/carduser/addcard/card_id/" . $arr['card_id'] . "/openid/" . $arr['openid'],
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => "卡券赠送提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => $arr['name'], 'color' => '#000'],
                'keyword2' => ['value' => $arr['title'], 'color' => '#FF0000'],
                'keyword3' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
            )
        );
        $res = $weObj->sendTemplateMessage($template);
        return $res;
    }

    //获取代理商域名
//    public function getagenturl($card_id){
//        $CardMember = new CardMember();
//        $Merchant = new Merchant();
//        $Agent=new Agent();
//        $mid = $CardMember->where('card_id', $card_id)->value('mid');
//        $agent_id = $Merchant->where(['id'=>$mid])->value('agent');
//        $agent_url = $Agent->where(['id'=>$agent_id])->value('open_url');
//        return 'https://'.$agent_url;
//    }


    //充值赠送卡券
    public function tpl_zs_mesg_list($arr)
    {
        $System = new System();
        $WxOpen = new WxOpen();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $mid = $this->getmid($arr['card_id']);
        $map['id'] = $mid;
        $merchantiinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantiinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantiinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $weObj = new Wxobjopen($options);
        //模板ID
        $OpenTemplate = new OpenTemplate();
        $templateid = $OpenTemplate->where(['type' => 'card_zs_tpl', 'wx_open_id' => $mab['id']])->value('template_id');
        $Platurl = new Platurl();
        $agent_url = $Platurl->getagenturl('card_id', $arr['card_id']);
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => $templateid,
            'url' => $agent_url . "/mobile.php/carduser/addcardlist/openid/" . $arr['openid'] . "/give/" . $arr['give'] . '/card_id/' . $arr['card_id'],
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => "卡券赠送提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => $arr['name'], 'color' => '#000'],
                'keyword2' => ['value' => $arr['title'], 'color' => '#FF0000'],
                'keyword3' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
            )
        );
        $res = $weObj->sendTemplateMessage($template);
        return $res;
    }


    //根据card_id获取Mid
    public function getmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }



    public function orderinfo()
    {
        $request = request();
        //广告
        $Adview = new Adview();
        $ad_type = $Adview->getadtype($request->param('orderid'));
//        file_put_contents('/data2/html/payos/payad.txt', json_encode($ad_type), 8);
        if ($ad_type['ad_type'] == '1') {
            $Adview->getadvert($request->param('orderid'));
        }


        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $System = new System();

        $map['id'] = $request->param('id');
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
//        $config2 = $System->where(array('id' => 1))->find();
        $options = array(
            'component_token' => $agent['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $agent['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $agent['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $agent['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $agent['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );

        $weObj = new Wxobjopen($options);
        $openid = Session::get('openid');
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Wxpay/orderinfo", array('orderid' => $request->param('orderid'),'id' => $request->param('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {

                $openid = $info['openid'];

            }
        }
        $maq['orderid'] = $request->param('orderid');

        $Paylog = new Paylog();
        $order = $Paylog->where($maq)->find();
        $order['deduzkinfo'] = $this->getdeduzkinfo($order['hx_card'], $order['gel_card_zk']);
//        var_dump($order['openid']);
        if ($openid == $order['openid']) {

            $mav['id'] = $request->param('id');
            $Merchant = new Merchant();
            $shmc = $Merchant->where($mav)->value('merchant');


            $this->assign('shmc', $shmc);
            $this->assign('order', $order);
            $this->assign('id', $request->param('id'));
            $this->assign('orderid', $request->param('orderid'));
        } else {
            $this->error('非订单支付者无法查看订单详情');
        }
        //jssdk
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $jssdk = $weObj->getJsSign($url);
        $this->assign('jssdk', $jssdk);
        $this->assign('jssdk', $jssdk);
        //EMD
        $CardUserGet = new CardUserGet();
        $usercard  = $CardUserGet->where(['top_mid'=>$config['top_mid'],'card_type'=>'MEMBER_CARD','openid'=>$openid,'have'=>1,'fire'=>1,'is_del'=>1])->find();
        //是否有会员卡
        $domain = $request->domain();
        if ($usercard) {
            $mecard['url'] = $domain."/mobile.php?s=/carduser/mecard/card_id/".$usercard['card_id'];
        }else{
            $mecard['url'] = $domain."/mobile.php?s=/cardusernu/getcardlistnu/mid/".$order['mid'];
        }
        $this->assign('mecard', $mecard);

        return $this->fetch('index/orderinfo');
    }

    public function get_user_info($openid = 'ok2ajuAJm7owX6UaYGoQZ05YFcww', $id = 1)
    {
        $us['openid'] = $openid;
        $Wxuser = new WxUser();
        $user = $Wxuser->where("openid='$openid'")->count();
        if ($user == 0) {
            $map['id'] = $id;
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $System = new System();
            $user = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $user['agent']))->find();
//            $config = $System->where(array('id' => 1))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $options = array(
                'component_token' => $agent['component_token'], // 填写你设定的key
                'component_encodingaeskey' => $agent['component_encodingaeskey'], // 填写加密用的EncodingAESKey
                'component_appid' => $agent['component_appid'], // 填写高级调用功能的app id
                'component_appsecret' => $agent['component_appsecret'], // 填写高级调用功能的密钥
                'open_ticket' => $agent['open_ticket'],
                'authorizer_appid' => $users['authorizer_appid'],
                'authorizer_refresh_token' => $users['authorizer_refresh_token'],
            );
            $weObj = new Wxobjopen ($options);
            $userinfo = $weObj->getUserInfo($openid);
            $userinfo = json_encode($userinfo);


            $data['openid'] = $openid;
            $data['wx_info'] = $userinfo;
            $data['addtime'] = time();
            $add = $Wxuser->save($data);

        }
    }

    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        //  Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }
//    public function testfz(){
//        $Paylog=new Paylog();
//        $id=$Paylog->order('id desc')->find();
//        $this->fenzhang($id);
//    }

    private function fenzhang($param)
    {


    }
}